<?php

namespace app\admin\controller;
use app\admin\validate\CoinAddressValidate;
use app\service\ArticleService;
use app\admin\validate\ArticleValidate;
use think\exception\ValidateException;
use app\service\CategoryService;

class Article extends Admin
{
    public function __construct(ArticleService $service)
    {
        parent::__construct();
        $this->service = $service;
    }

    public function add()
    {
        if (!$this->request->isPost()) {
            $this->assign("title", "添加文章");
            $categoryService = $this->app->make(CategoryService::class);
            $categoryList = $categoryService->getAll(["status" => \app\model\Category::CATEGORY_STATUS_ACTIVE], "id,name", "id asc");
            $this->assign("categoryList", $categoryList);
            $this->assign("vo", null);
            return $this->fetch("form");
        }
        return $this->save();
    }

    public function index()
    {
        if (!$this->request->isPost()) {
            $this->assign("title", "文章列表");
            $categoryService = $this->app->make(CategoryService::class);
            $categoryList = $categoryService->getAll(["status" =>\app\model\Category::CATEGORY_STATUS_ACTIVE], "id,name", "id asc");
            $this->assign("category", json_encode($categoryList));
            return $this->fetch("index");
        }
        $params = $this->request->post();;
        $ret = $this->service->getList($params, "*", ["categories" => function ($query) {
            $query->field("id,name");
        }]);
        $this->result($ret);
    }

    private function save()
    {
        $params = $this->request->Post();
        $action = $this->request->action();
        $content = $this->request->post("content","",false);
        $data = [
            "title" => $params["title"],
            "id" => isset($params["id"]) ? $params["id"] : 0,
            "sort" => $params["sort"],
            "desc" => $params["desc"],
            "content" => $content,
            "thumb" => $params["thumb"],
            "category_id" => $params["category_id"] ?? []
        ];
        try {
            validate(ArticleValidate::class)->scene($action)->check($data);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $ret = $this->service->saveAll($data);
        if ($ret) {
            $this->success("操作成功", "/article/index");
        } else {
            $this->error("保存失败");
        }
    }

    public function edit()
    {
        if (!$this->request->isPost()) {
            $id = $this->request->get("id");
            if (!$id) {
                throw new ValidateException("缺少id");
            }
            $categoryService = $this->app->make(CategoryService::class);
            $categoryList = $categoryService->getAll(["status" =>\app\model\Category::CATEGORY_STATUS_ACTIVE], "id,name", "id asc")->toArray();
            $this->assign("title", "编辑文章");
            $vo = $this->service->get($id, ['*'], ["categories" => function ($query) {
                $query->field("id")->column("id");
            }]);
            $selectCategoryIds =[];
            foreach ($vo->categories as $category) {
                $selectCategoryIds[] = $category->id;
            }
            foreach ($categoryList as $key=>$category) {
                $categoryList[$key]["checked"] = 0;
                if (in_array($category["id"],$selectCategoryIds)) {
                     $categoryList[$key]["checked"] = 1;
                }
            }
            $this->assign("vo", $vo);
            $this->assign("categoryList", $categoryList);
            return $this->fetch("form");
        }
        $this->save();
    }

    public function status()
    {
        $params = $this->request->Post();
        try {
            validate(ArticleValidate::class)->scene("status")->check($params);
        } catch (ValidateException $e) {
            $this->error($e->getError());
        }
        $ret = $this->service->setStatus($params["id"], $params["status"]);
        if ($ret) {
            $this->success("设置成功");
        } else {
            $this->error("设置失败");
        }
    }
}